package com.atguigu.gmall.realtime.dwd.log.split.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.common.base.BaseApp;
import com.atguigu.gmall.realtime.common.constant.Constant;
import com.atguigu.gmall.realtime.common.util.DateFormatUtil;
import com.atguigu.gmall.realtime.common.util.FlinkSinkUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.kafka.sink.KafkaSink;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: DwdBaseLog
 * Description:
 *
 * @Create 2024/4/19 9:41
 */
public class DwdBaseLog extends BaseApp {
    private final String START = "start";
    private final String ERR = "err";
    private final String DISPLAY = "display";
    private final String ACTION = "action";
    private final String PAGE = "page";

    public static void main(String[] args) {
        new DwdBaseLog().start(10011, 4, "dwd_base_log", Constant.TOPIC_LOG);
    }

    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> kafkaSourceDS) {
        //TODO 对读取到流中的数据进行类型转换  并ETL
        SingleOutputStreamOperator<JSONObject> jsonObjDS = etl(kafkaSourceDS);


        //TODO 使用Flink的状态编程，修复老访客标记
        SingleOutputStreamOperator<JSONObject> fixedDS = fixNewOrOld(jsonObjDS);


        //TODO 按照日志类型进行分流   页面（主流）、错误、启动、曝光、动作
        Map<String, DataStream> dsMap = splitStream(fixedDS);


        //TODO 将不同流的数据写入到对应的kafka主题
        dsMap
                .get(ERR)
                .sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ERR));
        dsMap
                .get(START)
                .sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_START));
        dsMap
                .get(DISPLAY)
                .sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_DISPLAY));
        dsMap
                .get(ACTION)
                .sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ACTION));
        dsMap
                .get(PAGE)
                .sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_PAGE));
    }

    private Map<String, DataStream> splitStream(SingleOutputStreamOperator<JSONObject> fixedDS) {
        //定义侧输出流标签
        OutputTag<String> errTag = new OutputTag<String>("errTag") {
        };
        OutputTag<String> startTag = new OutputTag<String>("startTag") {
        };
        OutputTag<String> displayTag = new OutputTag<String>("displayTag") {
        };
        OutputTag<String> actionTag = new OutputTag<String>("actionTag") {
        };

        //分流
        SingleOutputStreamOperator<String> pageDS = fixedDS.process(
                new ProcessFunction<JSONObject, String>() {

                    @Override
                    public void processElement(JSONObject jsonObj, ProcessFunction<JSONObject, String>.Context context, Collector<String> out) throws Exception {
                        //处理错误日志
                        JSONObject errJsonObj = jsonObj.getJSONObject("err");
                        if (errJsonObj != null) {
                            context.output(errTag, jsonObj.toJSONString());
                            //将来写到页面日志
                            jsonObj.remove("err");
                        }

                        JSONObject startJsonObj = jsonObj.getJSONObject("start");
                        if (startJsonObj != null) {
                            //处理启动日志
                            context.output(startTag, jsonObj.toJSONString());
                        } else {
                            //处理页面日志
                            //获取页面日志中都应该有的三个属性 common、page、ts
                            JSONObject commonJsonObj = jsonObj.getJSONObject("common");
                            JSONObject pageJsonObj = jsonObj.getJSONObject("page");

                            Long ts = jsonObj.getLong("ts");
                            //JSONObject ts = jsonObj.getJSONObject("ts");

                            //处理曝光日志
                            JSONArray displayArr = jsonObj.getJSONArray("displays");
                            //判断是否有曝光信息
                            if (displayArr != null && displayArr.size() > 0) {
                                //遍历曝光数组，获取每一条曝光数据
                                for (int i = 0; i < displayArr.size(); i++) {
                                    JSONObject displayJsonObj = displayArr.getJSONObject(i);
                                    //定义新的json，用于封装曝光对象
                                    JSONObject newDisplayJsonObj = new JSONObject();
                                    newDisplayJsonObj.put("common", commonJsonObj);
                                    newDisplayJsonObj.put("page", pageJsonObj);
                                    newDisplayJsonObj.put("display", displayJsonObj);
                                    newDisplayJsonObj.put("ts", ts);

                                    context.output(displayTag, newDisplayJsonObj.toJSONString());
                                }
                                jsonObj.remove("displays");
                            }

                            //处理动作日志
                            JSONArray actionArr = jsonObj.getJSONArray("actions");
                            //判断是否有曝光信息
                            if (actionArr != null && actionArr.size() > 0) {
                                //遍历曝光数组，获取每一条曝光数据
                                for (int i = 0; i < actionArr.size(); i++) {
                                    JSONObject actionJsonObj = actionArr.getJSONObject(i);
                                    //定义新的json，用于封装曝光对象
                                    JSONObject newActionJsonObj = new JSONObject();
                                    newActionJsonObj.put("common", commonJsonObj);
                                    newActionJsonObj.put("page", pageJsonObj);
                                    newActionJsonObj.put("action", actionJsonObj);

                                    context.output(actionTag, newActionJsonObj.toJSONString());
                                }
                                jsonObj.remove("actions");
                            }

                            //将页面日志写入主流
                            out.collect(jsonObj.toJSONString());

                        }
                    }
                }
        );

        SideOutputDataStream<String> errDS = pageDS.getSideOutput(errTag);
        SideOutputDataStream<String> startDS = pageDS.getSideOutput(startTag);
        SideOutputDataStream<String> displayDS = pageDS.getSideOutput(displayTag);
        SideOutputDataStream<String> actionDS = pageDS.getSideOutput(actionTag);

        pageDS.print("页面:");
        errDS.print("错误:");
        startDS.print("启动:");
        displayDS.print("曝光:");
        actionDS.print("启动:");

        Map<String, DataStream> dsMap = new HashMap<>();
        dsMap.put(ERR, errDS);
        dsMap.put(START, startDS);
        dsMap.put(DISPLAY, displayDS);
        dsMap.put(ACTION, actionDS);
        dsMap.put(PAGE, pageDS);

        return dsMap;
    }

    private static SingleOutputStreamOperator<JSONObject> fixNewOrOld(SingleOutputStreamOperator<JSONObject> jsonObjDS) {
        //按照设备id进行分组
        KeyedStream<JSONObject, String> keyedDS = jsonObjDS.keyBy(t -> t.getJSONObject("common").getString("mid"));

        //修复
        SingleOutputStreamOperator<JSONObject> fixedDS = keyedDS.process(
                new KeyedProcessFunction<String, JSONObject, JSONObject>() {

                    private ValueState<String> lastVisitDateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        ValueStateDescriptor valueStateDescriptor = new ValueStateDescriptor<>("lastVisitDateState", String.class);
                        /*
                        valueStateDescriptor.enableTimeToLive(StateTtlConfig.newBuilder(Time.seconds(10))
                                .setStateVisibility(StateTtlConfig.StateVisibility.NeverReturnExpired)
                                .setUpdateType(StateTtlConfig.UpdateType.OnReadAndWrite)
                                .build());
                        */

                        lastVisitDateState = getRuntimeContext().getState(valueStateDescriptor);
                    }

                    @Override
                    public void processElement(JSONObject jsonObject, KeyedProcessFunction<String, JSONObject, JSONObject>.Context context, Collector<JSONObject> collector) throws Exception {
                        String lastVisitDate = lastVisitDateState.value();
                        Long ts = jsonObject.getLong("ts");

                        String curVisitDate = DateFormatUtil.tsToDate(ts);

                        String isNew = jsonObject.getJSONObject("common").getString("is_new");

                        //① 如果is_new的值为1
                        if ("1".equals(isNew)) {
                            //如果键控状态为null，认为本次是该访客首次访问 APP，将日志中 ts 对应的日期更新到状态中，不对 is_new 字段做修改；
                            if (StringUtils.isEmpty(lastVisitDate)) {
                                lastVisitDateState.update(curVisitDate);
                                //如果键控状态不为null，且首次访问日期不是当日，说明访问的是老访客，将 is_new 字段置为 0；
                            } else {
                                if (!lastVisitDate.equals(curVisitDate)) {
                                    isNew = "0";
                                    jsonObject.getJSONObject("common").put("is_new", isNew);
                                }
                                //如果键控状态不为 null，且首次访问日期是当日，说明访问的是新访客，不做操作；
                            }

                        } else {
                            //② 如果 is_new 的值为 0
                            //如果键控状态为 null，说明访问 APP 的是老访客但本次是该访客的页面日志首次进入程序。当前端新老访客状态标记丢失时，日志进入程序被判定为新访客，Flink 程序就可以纠正被误判的访客状态标记，只要将状态中的日期设置为今天之前即可。本程序选择将状态更新为昨日；
                            if (StringUtils.isEmpty(lastVisitDate)) {
                                long yesterdayTs = ts - 24 * 60 * 60 * 1000;
                                String yesterday = DateFormatUtil.tsToDate(yesterdayTs);
                                lastVisitDateState.update(yesterday);
                            }
                            //如果键控状态不为 null，说明程序已经维护了首次访问日期，不做操作。
                        }
                        collector.collect(jsonObject);


                    }
                }
        );
        return fixedDS;
    }

    private static SingleOutputStreamOperator<JSONObject> etl(DataStreamSource<String> kafkaSourceDS) {
        //定义侧输出流标签 ——标记脏数据
        OutputTag<String> dirtyTag = new OutputTag<String>("dirtyTag") {
        };
        //ETL
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaSourceDS.process(
                new ProcessFunction<String, JSONObject>() {
                    @Override
                    public void processElement(String jsonStr, ProcessFunction<String, JSONObject>.Context context, Collector<JSONObject> out) throws Exception {
                        try {
                            JSONObject jsonObject = JSON.parseObject(jsonStr);
                            //如果没发生异常说明是标准的json，直接向下游传递
                            out.collect(jsonObject);
                        } catch (Exception e) {
                            //发生异常说明不是标准json，属于脏数据，放入侧输出流
                            context.output(dirtyTag, jsonStr);
                        }
                    }
                }
        );
        //jsonObjDS.print();
        SideOutputDataStream<String> dirtyDS = jsonObjDS.getSideOutput(dirtyTag);
        //jsonObjDS.getSideOutput(dirtyTag).print("脏数据");

        //将侧输出流中的脏数据写到kafka对应主题
        KafkaSink<String> kafkaSink = FlinkSinkUtil.getKafkaSink("dirty_data");
        dirtyDS.sinkTo(kafkaSink);
        return jsonObjDS;
    }
}
